package com.project.dao.impl;

import com.project.bean.CutPageBean;
import com.project.bean.GoodsBean;
import com.project.dao.IGoodsDao;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
@Repository
public class GoodsDaoImpl extends BaseDao implements IGoodsDao {
    @Override
    public CutPageBean<GoodsBean> findByItem(Integer pageNo, String name) {
        this.setConnection();
        CutPageBean<GoodsBean> cut = new CutPageBean<>();
        String sql = "SELECT p.*,COUNT(s.`pk_assessId`) goodsNum FROM t_goods p LEFT JOIN t_assess s ON s.`fk_goodsId`=p.`pk_goodsId` ";
        String dynSql=" where 1 = 1 ";
        if (name!=null&&name.length()!=0){
            dynSql+="and t_name like '%"+name+"%'";
        }
        try {
            ps =con.prepareStatement(sql+dynSql+" GROUP BY p.`pk_goodsId` LIMIT ?,?");
            ps.setObject(1,(pageNo-1)*CutPageBean.PAGESIZE);
            ps.setObject(2,CutPageBean.PAGESIZE);
            rs = ps.executeQuery();
            while (rs.next()){
            cut.getList().add(this.getUser());
            }

            ps = con.prepareStatement("select  count(*) c from  t_goods "+dynSql);
            rs=ps.executeQuery();
            if (rs.next()){
                cut.setCount(rs.getInt("c"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            this.closeConnection();
        }
        return cut;
    }

    @Override
    public GoodsBean findById(int id) {
        this.setConnection();
        GoodsBean goods = null;
        try {
            ps=con.prepareStatement("SELECT p.*,COUNT(s.`pk_assessId`) goodsNum FROM t_goods p LEFT JOIN t_assess s ON s.`fk_goodsId`=p.`pk_goodsId` where p.pk_goodsId=?");
            ps.setObject(1,id);
            rs=ps.executeQuery();
            if (rs.next()){
              goods = this.getUser();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
       finally {
            this.closeConnection();
        }
        return goods;
    }

    public GoodsBean getUser(){
        GoodsBean goods = new GoodsBean();
        try {
            goods.setGoodsName(rs.getString("t_name"));
            goods.setId(rs.getInt("pk_goodsId"));
            goods.setMoney(rs.getInt("t_money"));
            goods.setImgPath(rs.getString("t_imagPath"));
            goods.setAssessNum(rs.getInt("goodsNum"));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return goods;
    }

    public static void main(String[] args) {
        IGoodsDao dao = new GoodsDaoImpl();
        System.out.println(dao.findById(2));
    }
}
